<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>拖拽demo</title>
    <script src="js/jquery-1.11.1.js"></script>
    <script>
        $(function(){
            var _obj = $("#dragBox");
            var _container = $(".container");

            var movestart = function(e){


                var _x = e.pageX;
                var _y = e.pageY;
                var _startX = $(_obj).offset().left;
                var _startY = $(_obj).offset().top;
                console.log("----_x----"+_x+"----_startX-------"+_startX)

                var move = function(e){
                    var _left = e.pageX - _x + _startX;
                    var _top = e.pageY - _y + _startY;

                    if(_top < _container.offset().top){
                        _top = _container.offset().top;
                    }

                    if(_top > _container.offset().top + _container.height() - _obj.height()){
                        _top = _container.offset().top + _container.height() - _obj.height();
                    }

                    if(_left < _container.offset().left){
                        _left = _container.offset().left;
                    }

                    if(_left > _container.offset().left + _container.width() - _obj.width()){
                        _left = _container.offset().left + _container.width() - _obj.width();
                    }

                    $(_obj).css({left:_left,top:_top});
                };

                var movestop = function(){
                    $(document).unbind("mousemove");
                    $(document).unbind("mouseup");
                };



                $(document).bind("mousemove",move);
                $(document).bind("mouseup",movestop);
            };


            $(document).bind("mousedown",movestart)
        })
    </script>
</head>
<style>
    .container{width: 800px;height: 600px;border: 1px solid #ccc;margin: 0 auto;}
    #dragBox{width: 80px;height: 80px;background-color: #660033;position: absolute;}
</style>
<body>
    <div class="container">
        <div id="dragBox"></div>
    </div>
</body>
</html>